using System;
using UnityEngine;

public class ObjectPool : MonoBehaviour
{
	public GameObject prefab;

	public int initialSize = 24;

	public int reallocationSize = 24;

	public GameObject[] _pool;

	private int _poolSize;

	private int _index = -1;

	private void Start()
	{
		if (_pool == null)
		{
			Reallocate();
		}
	}

	public void ResetAll()
	{
		GameObject[] pool = _pool;
		foreach (GameObject gameObject in pool)
		{
			gameObject.SetActive(value: false);
		}
	}

	public T GetNext<T>() where T : MonoBehaviour
	{
		return GetNext().GetComponent<T>();
	}

	public GameObject GetNext()
	{
		for (int i = 1; i < _poolSize; i++)
		{
			_index = (_index + i) % _poolSize;
			GameObject gameObject = _pool[_index];
			if (!gameObject.activeSelf)
			{
				gameObject.SetActive(value: true);
				return gameObject;
			}
		}
		Reallocate();
		return GetNext();
	}

	public void Reallocate()
	{
		if (_pool == null)
		{
			_pool = new GameObject[initialSize];
			for (int i = 0; i < initialSize; i++)
			{
				_pool[i] = CreatePoolObject();
				_pool[i].name = $"Pool UnityEngine.Object {i}";
			}
		}
		else
		{
			Array.Resize(ref _pool, _pool.Length + reallocationSize);
			for (int j = 0; j < reallocationSize; j++)
			{
				_pool[_pool.Length - j - 1] = CreatePoolObject();
				_pool[_pool.Length - j - 1].name = $"Pool UnityEngine.Object {_pool.Length - j - 1}";
			}
		}
		_poolSize = _pool.Length;
	}

	private GameObject CreatePoolObject()
	{
		GameObject gameObject = UnityEngine.Object.Instantiate(prefab);
		gameObject.transform.SetParent(base.transform, worldPositionStays: false);
		gameObject.SetActive(value: false);
		return gameObject;
	}
}
